package com.renchunlin.loginkeyboard.view

import android.content.Context
import android.graphics.Color
import android.text.Editable
import android.text.InputFilter
import android.text.InputFilter.LengthFilter
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.CheckBox
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.TextView
import com.renchunlin.loginkeyboard.R


/*
 * class title:
 * 点击获取验证码-->条件手机号码是正确的
 * 点击登录-->条件正确的手机号码+验证码+同意了协议
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/6/21.
 * PS: Not easy to write code, please indicate.
 */
class LoginPageView : FrameLayout {

    companion object {
        const val SIZE_VERIFY_CODE_DEFAULT = 4
    }

    private val mainColor = Color.WHITE
    private val verifyCodeSize = SIZE_VERIFY_CODE_DEFAULT
    private var mColor = 0
    private var mVerifyCodeSize = 0
    private lateinit var onLoginPageActionListener: OnLoginPageActionListener
    private lateinit var loginKeyBoard: LoginKeyBoard
    private lateinit var phoneNumInp: EditText
    private lateinit var verifyCodeInput: EditText
    private lateinit var getVerifyCodeBtn: TextView
    private lateinit var mLoginBtn: TextView
    private lateinit var mIsConfirm: CheckBox

    //是否输入手机号码
    private var isPhoneNumOk = false

    //是否同意用户协议
    private var isAgreementOk = false

    //是否输入验证码
    private var isVerifyCodeOk = false

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        //初始化属性
        initAttrs(context, attrs)
        //初始化控件
        initView()
        //禁止弹出软键盘
        disableEdtFocus2Keypad()
        initEvent()
    }

    private fun disableEdtFocus2Keypad() {
        //当获取到焦点，弹出软键盘（true 弹出 false 禁止弹出）
        phoneNumInp.showSoftInputOnFocus = false
        verifyCodeInput.showSoftInputOnFocus = false
    }

    private fun initView() {
        LayoutInflater.from(context).inflate(R.layout.login_page_view, this)
        mIsConfirm = this.findViewById(R.id.report_check_box)
        verifyCodeInput = this.findViewById(R.id.verify_code_input_box)
        loginKeyBoard = this.findViewById(R.id.number_key_pad)
        phoneNumInp = this.findViewById(R.id.phone_num_input_box)
        getVerifyCodeBtn = this.findViewById(R.id.get_verify_code_btn)
        mLoginBtn = this.findViewById(R.id.login_btn)

        //设置主题颜色
        if (mColor != 0) {
            mIsConfirm.setTextColor(mColor)
        }

        //设置验证码长度
        verifyCodeInput.filters = arrayOf<InputFilter>(LengthFilter(mVerifyCodeSize))
        updateAllBtnState()
    }

    private fun initEvent() {
        loginKeyBoard.setOnKeyPressListener(object : LoginKeyBoard.OnKeyPressListener {
            override fun onNumberPress(number: Int) {
                //数字被点击
                //插入数字
                val focusEdit = getFocusEdit()
                if (focusEdit != null) {
                    val text = focusEdit.text
                    val index = focusEdit.selectionEnd
                    text.insert(index, number.toString())
                }
            }

            override fun onBackPress() {
                val focusEdit = getFocusEdit()
                if (focusEdit != null) {
                    val index = focusEdit.selectionEnd
                    val text = focusEdit.text
                    if (index > 0) {
                        text.delete(index - 1, index)
                    }
                }
            }

        })

        //获取验证码
        getVerifyCodeBtn.setOnClickListener {

        }

        //监听手机号码
        phoneNumInp.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                //变化的时候去检查手机号码是否符合格式
                val phoneNum = s.toString()
                isPhoneNumOk = phoneNum.length == 11
                updateAllBtnState()

            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        //登录
        mLoginBtn.setOnClickListener {

        }

        verifyCodeInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val toString = s.toString()
                isVerifyCodeOk = toString.length == verifyCodeSize
                updateAllBtnState()
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })

        mIsConfirm.setOnCheckedChangeListener { _, isChecked ->
            isAgreementOk = isChecked
            updateAllBtnState()
        }
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?) {
        val typeArray =
            context.obtainStyledAttributes(attrs, R.styleable.LoginPageView)
        mColor = typeArray.getColor(R.styleable.LoginPageView_mainColor, mainColor)
        mVerifyCodeSize =
            typeArray.getInteger(R.styleable.LoginPageView_verifyCodeSize, verifyCodeSize)
        typeArray.recycle()
    }

    public fun setOnLoginPageActionListener(onLoginPageActionListener: OnLoginPageActionListener) {
        this.onLoginPageActionListener = onLoginPageActionListener
    }

    interface OnLoginPageActionListener {
        fun onGetVerifyCodeClick(phoneNum: String)
        fun onOpenAgreementClick()
        fun onConfirmClick(verifyCode: String, phoneNum: String)
    }

    /**
     * 获取当前有焦点的输入框
     * 使用时注意判空
     */
    private fun getFocusEdit(): EditText? {
        val view = this.findFocus()
        if (view is EditText) {
            return view
        }
        return null
    }


    private fun updateAllBtnState() {
        //判断验证码是否可以点击
        getVerifyCodeBtn.isEnabled = isPhoneNumOk
        mLoginBtn.isEnabled = isPhoneNumOk && isAgreementOk && isVerifyCodeOk
    }
}